<template>
  <div class="container" style="text-align: center">
    <h1 style="font-weight: bold">项目提交</h1>
    <form>

      <div class="container">
        <p class="title">上传文件</p>
        <!--表格信息-->
        <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            @change="updateFile"
        >
          <template #trigger>
            <el-button type="primary">选择上传的文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip text-red">
              只能上传一个文件，新的文件会被覆盖
            </div>
          </template>
        </el-upload>
      </div>
      <div class="container" >
        <p class="title">项目信息</p>
        <!--form表格-->
        <el-form
            :model="form"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
        >
<!--项目名称-->
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
<!--项目类别-->
          <el-form-item label="项目类别" prop="category">
            <el-select v-model="form.type" placeholder="选择类别">
              <el-option label="国创" value="国创" />
              <el-option label="校创" value="校创" />
            </el-select>
          </el-form-item>
<!--时间-->
          <el-form-item label="起止时间" required>
            <el-col :span="11">
              <el-form-item prop="date1">
                <el-date-picker
                    v-model="form.startTime"
                    type="date"
                    label="Pick a date"
                    placeholder="开始时间"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col class="text-center" :span="2">
              <span class="text-gray-500">-</span>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="date2">
                <el-date-picker
                    v-model="form.endTime"
                    type="date"
                    label="Pick a date"
                    placeholder="终止时间"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-form-item>
<!--项目金额-->
          <el-form-item label="项目金额" prop="money1">
            <el-input v-model="form.projectMoney" />
          </el-form-item>
<!--自然基金-->
          <el-form-item label="自然基金" prop="money2">
            <el-input v-model="form.naturalFund" />
          </el-form-item>
<!--合作单位-->
          <el-form-item label="合作单位" prop="factory">
            <el-input v-model="form.cooperationUnit" />
          </el-form-item>
<!--提交/取消-->
          <el-form-item label="项目描述" prop="describe">
            <el-input type="textarea" v-model="form.projectDescription"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>

      </div>
    </form>

  </div>

</template>

<script setup lang="ts">
import {onUpdated, reactive, ref} from 'vue'
import {ElMessage, genFileId} from 'element-plus'
import type { FormInstance, FormRules,UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import axios from "axios";

const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
}
//论文信息部分表格
let form = reactive({
  cooperationUnit: "",
  filePath: "",
  memberFiveName: "5",
  memberFourName: "4",
  memberThreeName: "3",
  memberTwoName: "2",
  memberOneName: "1",
  startEndYear: "",
  type: "",
  naturalFund: "",
  startTime: "",
  endTime: "",
  projectDescription: "",
  projectMoney: "",
  name: "",
  category: "",
})
var file = reactive({})
//项目信息相关
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()

const onSubmit = () => {
  console.log('submit!')
}
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
  ],
  region: [
    {
      required: true,
      message: '请选择项目类别',
      trigger: 'change',
    },
  ],
  money1: [
    {
      required: true,
      message: '请输入金额',
      trigger: 'change',
    },
  ],
  date1: [
    {
      type: 'date',
      required: true,
      message: '请选择起始日期',
      trigger: 'change',
    },
  ],
  date2: [
    {
      type: 'date',
      required: true,
      message: '选择终止日期',
      trigger: 'change',
    },
  ],
  type: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least one activity type',
      trigger: 'change',
    },
  ],
  describe: [
    {
      required: true,
      message: 'Please select activity resource',
      trigger: 'blur',
    },
  ],
})

onUpdated(()=>{
  form.startEndYear = form.startTime + form.endTime;
})
var file = reactive({});
const submitForm = () => {
  console.log(localStorage.getItem('ID'))
  axios.post(`project/add?cooperationUnit=${form.cooperationUnit}&filePath=${form.filePath}&memberFiveName=${form.memberFiveName}
                  &memberFourName=${form.memberFourName}&memberOneName=${form.memberOneName}&memberThreeName=${form.memberThreeName}
                  &memberTwoName=${form.memberTwoName}&name=${form.name}&naturalFund=${form.natureFund}&startEndYear=${form.startTime+'-'+form.endTime}&type=${form.type}
                  &projectDescription=${form.description}`,form, {
    headers:{
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    }
  }).then(res=>{
    if(res.data.code === 0){
      var projectID = res.data.data;
      let param = new FormData();//创建form对象
      console.log("file"+file);
      console.log("paperid"+projectID);
      if(JSON.stringify(file)==="{}") {
        ElMessage("请上传文件");
        return false;
      } else {
        param.append("file", file);//为创建的form对象增加上传的文件
        param.append("projectId", projectID);//如果需要上传其他字段，在这里增加
        let config = { headers: { 'Content-Type': 'multipart/form-data', 'session':localStorage.getItem('ID'),  } }//修改请求头
        let url = "project/upload";
        console.log(param);
        axios.post(url, param, config).then((res) => {
          console.log(res, "res");
          if(res.data.code === 0) {
            ElMessage("提交成功");
            router.push('/donate')
          } else {
            ElMessage("提交失败");
          }
        });
      }
    } else {
      ElMessage('提交失败')
    }
  })
  console.log('submit!')

}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
import { getCurrentInstance } from "vue";
import router from "../router";
const { proxy } = getCurrentInstance();//获取原型
const Axios = proxy.$axios;//Axios就是挂在的原型（相当于vue2中的this.$axios）
const updateFile = (e) => {
  console.log(e);
  file = e.raw;//拿到上传的file
}
</script>
<style>
.title{
  font-weight: bold;
  font-size: 20px;
}
.paper-info{
  width: 300px;
  height: 30px;
  font-size: 18px;
  border-radius: 5px;
}
</style>